<template>
  <div class="user-page" >
    <div class="user-page-head">
      <div class="top">
        <van-image round fit="cover" :src="avatar"  />
        <div class="name">
          <p>{{userInfoData.username}}</p>
          <p  @click="edit" ><van-icon name="edit"  />编辑个人信息</p>
        </div>
      </div>
      <van-row>
        <van-col  span="6">
         <router-link class="custom-link" to="/articleStore">
          <p>{{favorite_num}}</p>
          <p>收藏</p>
        </router-link>
          
        </van-col>
        <van-col span="6">
          <router-link class="custom-link" to="/test">
            <p>8</p>
            <p>关注</p>
          </router-link>
         
        </van-col>
        <van-col span="6">
          <router-link class="custom-link" to="/test">
             <p>999+</p>
            <p>积分</p>
          </router-link>
         
        </van-col>
        <van-col span="6">
          <router-link class="custom-link" to="/test">
            <p>66+</p>
            <p>优惠券</p>
          </router-link>
         
        </van-col>
      </van-row>
    </div>
    <div class="user-page-order">
      <div class="head">
        <h3>咨询订单</h3>
        <router-link to="">全部订单 <van-icon name="arrow" /></router-link>
      </div>
      <van-row>
        <van-col span="6">
          <van-badge >
            <gh-icon name="user-paid" />
          </van-badge>
          <p>待付款</p>
        </van-col>
        <van-col span="6">
          <van-badge >
            <gh-icon name="user-shipped" />
          </van-badge>
          <p>待咨询</p>
        </van-col>
        <van-col span="6">
          <van-badge >
            <gh-icon name="user-received" />
          </van-badge>
          <p>待评价</p>
        </van-col>
        <van-col span="6">
          <van-badge >
            <gh-icon name="user-finished" />
          </van-badge>
          <p>已完成</p>
        </van-col>
      </van-row>
    </div>
    <!-- 工具栏 -->
    <div class="user-page-group">
      <h3>快捷工具</h3>
      <van-cell
        v-for="(item, i) in filteredTools"
        :key="i"
        :title="item.label"
        :to="item.path"
        is-link
        :border="false"
      >
        <template #icon><gh-icon  :name="`user-tool-0${1 + i}`" /></template>
      </van-cell>
    </div>
    <a class="logout"  @click="logout" href="javascript:;">退出登录</a>
  </div>
 
</template>
  
<script setup>
import {ref,onMounted,onUnmounted,onBeforeMount }from 'vue'
import {useRouter} from 'vue-router'
import {useUserStore}from '@/stores'
import { Toast, Dialog } from 'vant';
import {baseURL} from '@/utils/request.js'
import { getImage,getUserInfo } from '@/services/user'
import { getFavoriteStoreNum } from '@/services/article'
import{getconsultantInfoByName,getuseridByaccount} from '@/services/others'
import 'vant/es/toast/style'
import axios from 'axios'
// import { getUserInfo } from '@/services/user'


// 响应变量存取用户数据
const user = ref({})
const avatar=ref()
//用户的id数据
const userId=ref('')
//收藏文章的数量
const favorite_num=ref('')
// 获取用户数据
onBeforeMount(async () => {
  const newUserInfo=await getUserInfo(userInfo.account).then((data)=>{
    return data
  }).catch((error)=>{
    return error
  })
  // console.log(newUserInfo)
  // store.delUser()
  store.setUser(newUserInfo.data.data,  localStorage.getItem('tokenStr'))
//  localStorage.setItem('tokenStr',newUserInfo.data.token)
 userInfoData.value = newUserInfo.data.data
 
  const pic= userInfo.avatar
  const res=await getImage(pic).then((data)=>{
    return data
  }).catch((error)=>{
    return error
  })
  // console.log(res.data.base64Chunks)
  let imageData
  for(let i = 0; i < res.data.base64Chunks.length; i++) {
    // 合并分块 Base64 数据
   const base64Data = res.data.base64Chunks.join('');
    imageData = `data:image/jpeg;base64,${base64Data}`;
}
  avatar.value = imageData // 将 res.data 赋值给 user 的 value
  const account=JSON.parse(localStorage.getItem('gh-user')).user.userData.account
  const user_id=await getuseridByaccount(account)
  userId.value=user_id.data.id
  const favoriteNum=await  getFavoriteStoreNum(userId.value)
  favorite_num.value=favoriteNum.data
  // const res = await getUserInfo()
  // user.value = res.data
 })

const userInfoData = ref(JSON.parse(localStorage.getItem('gh-user')).user.userData)
const userData=localStorage.getItem('gh-user')
// console.log(userData)
const userObj=JSON.parse(userData)
const userInfo=userObj.user.userData;
const token=userObj.user.token ;
onMounted(async()=>{
  if(!localStorage.getItem('gh-user')){
    router.push('/login')
  }

  // store.delUser()

})
// 获取图片函数
const getImageUrl=(relativePath)=> {
      const serverBaseUrl = baseURL; // 替换成实际的服务器基础 URL
      const base64Image= serverBaseUrl + relativePath;
    return base64Image
}
getImageUrl(userInfo.avatar)


// console.log(pic)

// tools数据
const tools = [
  { label: '我的预约', path: '/appointment/bookingHistory' }, //预约历史
  { label: '阅读历史', path: '/readHistory' },
  { label: '安全中心', path: '/safeCenter' },
  { label: '官方客服', path: '/customerService' },
  {label:'咨询师入口',path:'/consultant-admin'},
  { label: '系统后台管理', path: '/admin' },
  { label: '设置', path: '/set' }
]
//判断用户权限对工具栏进行过滤
const filterTools = (loginRole) => {
    if (loginRole === 'admin') {
        return tools.filter(tool => tool.label !== '咨询师入口');
    } else if (loginRole === 'normal') {
        return tools.filter(tool => tool.label !== '咨询师入口' && tool.label !== '系统后台管理');
    } else if (loginRole === 'counselor') {
        return tools.filter(tool => tool.label !== '系统后台管理');
    } else {
        return tools;
    }
}

const loginRole =JSON.parse(localStorage.getItem('gh-user')).user.userData.role; // 设置登录者的角色，可以根据实际情况更改
// console.log(loginRole)
const filteredTools = filterTools(loginRole);
// console.log(filteredTools);

// 退出登录
const store = useUserStore()
const router = useRouter()
const logout = async () => {
  await Dialog.confirm({
    title: '温馨提示',
    message: '您确认退出登录吗？'
  })
   .then(() => {
    store.delUser()
    localStorage.removeItem('tokenStr')
    router.push('/login')
    Toast.success('您已退出登录')
  })
  .catch(() => {
    Toast('取消操作')
  });
}

 const edit = async () => {
  router.push('/editUserInfo')
  
}

 
</script>

  <style lang="scss" scoped>

 @import '@/styles/user.scss';

  </style>